import './style.scss'
import { getDictByType } from '@/api/dataDict'
const none = [undefined, null, '']
export default {
  name: 'ListItem',
  props: {
    label: {
      type: [String, Number],
      default: ''
    },
    value: {
      type: [String, Number, Array],
      default: ''
    },
    sep: {
      type: [String],
      default: ''
    },
    itemClassName: {
      type: [String],
      default: ''
    },
    labelClassName: {
      type: String,
      default: ''
    },
    labelWidth: {
      type: String,
      default: ''
    },
    valueClassName: {
      type: String,
      default: ''
    },
    dictTypeCode: {
      type: String,
      default: ''
    },
    appCode: {
      type: String,
      default: 'call-center'
    },
    domainCode: {
      type: String,
      default: 'marketing'
    },
    defaultValue: {
      type: String,
      default: ''
    },
    // 校验相关
    prop: {
      type: String,
      default: ''
    },
    rules: {
      type: Array,
      default: () => []
    },
    propValue: {
      type: [String, Array, Object, Number],
      default: ''
    }
  },
  data() {
    return {
      __value: '',
      errMsg: ''
    }
  },
  watch: {
    value: {
      handler: function(n, o) {
        if (this.dictTypeCode === '') return
        if (/,/.test(n) && typeof n === 'string') {
          n = n.split(',')
        }
        if (!(n instanceof Array)) {
          n = [n]
        }
        const t = []
        const { dictTypeCode, appCode, domainCode } = this
        getDictByType({ dictTypeCode, appCode, domainCode }).then(res => {
          for (const code of n) {
            for (const item of res.data) {
              if (item.dictCode.toString() === code.toString()) {
                t.push(item.dictName)
                continue
              }
            }
          }
          this.$set(this.$data, '__value', t.join(','))
        })
      },
      immediate: true
    }
  },
  computed: {
    isRequired() {
      return this.rules && this.rules.some(e => e.required)
    }
  },
  render(h) {
    // 如果content slot有内容则只渲染content
    if (this.$scopedSlots.content instanceof Function) {
      return this.$scopedSlots.content()
    }
    const items = []
    if (this.label !== '') {
      const childs = [this.label, h('span', {
        style: {
          // position: 'absolute',
          // right: '-3px'
        }
      }, this.sep)]
      if (this.isRequired) {
        childs.unshift(h('i', { class: 'custom-is-required' }, '*'))
      }
      items.push(h('span', { class: [this.labelClassName], style: { width: this.labelWidth, position: 'relative', paddingRight: '4px' }}, childs))
    }
    if (typeof this.$scopedSlots.default === 'function') {
      items.push(h('div', { class: ['slotItemContainer'], style: { width: '100%', display: 'inline-block' }}, this.$scopedSlots.default(this.value)))
    } else if (typeof this.$scopedSlots.icon === 'function') {
      const v_vnode = h('span', { class: [this.valueClassName], onicon: { click: () => { this.value !== undefined ? this.$emit('click', this.value) : '' } }}, this.$data.__value ? this.$data.__value : (!(none.includes(this.value)) ? this.value : this.defaultValue))
      const w_vnode = h('div', { class: ['slotItemContainer'], style: { width: '100%', display: 'inline-block' }}, [v_vnode, ...this.$scopedSlots.icon()])
      items.push(w_vnode)
    } else {
      items.push(h('span', { class: [this.valueClassName], on: { click: () => { this.value !== undefined ? this.$emit('click', this.value) : '' } }}, this.$data.__value ? this.$data.__value : (!(none.includes(this.value)) ? this.value : this.defaultValue)))
    }
    const vn = h('div', {
      class: [this.itemClassName, 'custom-list-item'],
      key: this.label
    }, items)
    if (this.errMsg) {
      const errVn = h('div', { class: 'custom-list-item-err-msg', style: { left: `${this.__labelWidth}px` }}, this.errMsg)
      return h('div', { class: 'custom-list-item-err', key: this.label + '1' }, [vn, errVn])
    }
    return vn
  },
  methods: {
    validate(root) {
      this.errMsg = ''
      this.getLabelWidth()
      if (!this.prop || (this.rules && this.rules.length === 0)) {
        return true
      }
      // const v = root[this.prop]
      const v = Object.prototype.toString.call(root) === `[object Object]` ? root[this.prop] : root
      for (const r of this.rules) {
        if (r.validator instanceof Function) {
          r.validator(r, v, this.callBack)
          if (this.errMsg) {
            break
          }
        } else if (r.required) {
          if (v instanceof Array && v.length === 0) {
            this.errMsg = r.message
            break
          }
          if (v === '' || v === undefined || v === null) {
            this.errMsg = r.message
            break
          }
        }
      }
      if (this.errMsg) {
        return { result: false, errMsg: this.errMsg }
      }
      return { result: true, errMsg: '' }
    },
    callBack(errMsg) {
      if (errMsg === undefined || errMsg === null || errMsg === '') {
        this.errMsg = ''
      } else if (errMsg instanceof Error) {
        this.errMsg = errMsg.message
      } else {
        this.errMsg = errMsg
      }
    },
    clearErrMsg() {
      this.errMsg = ''
    },
    getLabelWidth() {
      if (this.__labelWidth) {
        return
      }
      const el = this.$el.querySelector(`.${this.labelClassName}`)
      if (el) {
        this.__labelWidth = el.getBoundingClientRect().width
      }
    }
  },
  created() {
    if (this.prop && (this.rules && this.rules.length !== 0)) {
      this.$watch('propValue', () => {
        this.validate(this.propValue)
      })
    }
  }
}
